package cn.itcast.controller;


import cn.itcast.common.R;
import cn.itcast.entity.User;
import cn.itcast.service.IUserService;
import cn.itcast.util.SMSUtils;
import cn.itcast.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User  user){
      String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //发送短信
      //  SMSUtils.sendMessage("黑马旅游", "SMS_195723031", phone, code);

        log.info("短信验证码是:{}",code);
        //将验证码存进session
//        session.setAttribute(phone,code);
        //将验证码存进redis

        redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);


        return R.success("短信发送成功");
    }

    @PostMapping("login")
    public R<String> login(@RequestBody Map<String,String> map){
        String phone = map.get("phone");
        String code = map.get("code");
//        String sessionCode = (String) session.getAttribute(phone);
        //从redis获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (redisCode == null){
            return R.error("验证码过期");
        }
        if (!redisCode.equals(code)){
            return R.error("验证码错误");
        }
        redisTemplate.delete(redisCode);//删除redis的缓存
        User user =userService.findByPhone(phone);
        if (user == null){
            return R.error("您还未注册");
        }
        session.setAttribute("LOGIN_ID", user.getId());
        log.info("userId:{}存入Session",user.getId());
        return R.success(user.getName());
    }
}
